#include<iostream>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
#include<string>
#include<unistd.h>
const char* _path_name = ".";
int _proj_id = 0x92;


class Shm
{
private:
    bool SHM_GET(int flags)
    {
        _key = ftok(_path_name,1);
        _shmid = shmget(_key,_size,flags);
        if(_shmid < 0)
        {
            perror("shmget");
            return false;
        }
        return true;
    }
public:
    Shm()
    {}

    bool Creat()
    {
        return SHM_GET(IPC_CREAT | IPC_EXCL | 0666);
    }

    bool Get()
    {
        return SHM_GET(IPC_CREAT);
    }

    bool Remove()
    {
        int ret = shmctl(_shmid,IPC_RMID,nullptr);
        if(ret < 0)
        {
            perror("shmctl");
            return false;
        }
        return true;
    }

    bool Attch()
    {
        _start = shmat(_shmid,nullptr,0);
        if((long long int)_start < 0)
        {
            perror("shmat");
            return false;
        }
        return true;
    }

    bool Deatch()
    {
        int ret = shmdt(_start);
        if(ret < 0)
        {
            perror("shmdt");
            return false;
        }
        return true;
    }

    bool Send_Message()
    {
        std::cout << "发送消息: " << std::endl;
        std::getline(std::cin,_message);
        int i = 0;
        for(i = 0;i<_message.size();i++)
        {
            ((char*)_start)[i] = _message[i];
        }
        ((char*)_start)[i] = '\0';
        return true;
    }

    bool Recept_Message()
    {
        std::cout << "接收消息: ";
        _message = (char*)_start;
        std::cout << _message << std::endl;
        return true; 
    }

    
    ~Shm()
    {}

private:
    key_t _key = -1;
    int _shmid = -1;
    int _size = 4096;
    std::string _message;
    void* _start = nullptr;
};